package com.instalinks.android.lib;


import java.util.List;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.PowerManager;
import android.widget.Toast;

public class AppHelper {

	/**
	 * Check if the passed string is numeric or not
	 * 
	 * @param str
	 * @return
	 */
	public static final boolean isNumeric(String str) {
		try {
			@SuppressWarnings("unused")
			double d = Double.parseDouble(str);
		} catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}

	public static final boolean isValidPhoneNumber(String phoneNumber) {
		String cPhoneNumber = phoneNumber.replace("+", "").replace("(", "")
				.replace(")", "").replace("-", "").replace(" ", "")
				.replace(".", "");
		boolean result = cPhoneNumber.matches("^[0-9]{9,14}$");
		return result;
	}

	public static final boolean isValidShortCode(String shortCode) {
		boolean result = shortCode.matches("^[0-9]{3,8}$");
		return result;
	}

	/**
	 * Method to raise TOAST from any activity.
	 * 
	 * @param ctx
	 * @param message
	 */
	public static final void alert(Context ctx, String message) {
		Toast.makeText(ctx, message, Toast.LENGTH_LONG).show();
	}

	/**
	 * Wakeup Lock
	 * 
	 * @param timeout
	 *            timeout in milliseconds
	 */
	public static final void wakeUp(Context context, long timeout) {
		PowerManager pm = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(
				PowerManager.SCREEN_BRIGHT_WAKE_LOCK
						| PowerManager.ACQUIRE_CAUSES_WAKEUP, "[INSTALINKS]");
		wl.acquire(timeout);
	}

	/**
	 * Compare the application version code with given version code.
	 * 
	 * @param context
	 * @param versionCode
	 * @return
	 */
	public static final boolean isAppUpToDate(Context context, int versionCode) {
		Boolean result = false;

		try {
			PackageInfo pInfo = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			result = (pInfo.versionCode == versionCode);
		} catch (NameNotFoundException e) {
			result = false;
		}
		return result;
	}

	/***
	 * Method to register make your application/device register for C2dm
	 * notifications.
	 * 
	 * @param context
	 * @param appEmail
	 */
	public static final void registerForC2dm(Context context, String appEmail) {

		Intent registrationIntent = new Intent(
				"com.google.android.c2dm.intent.REGISTER");
		registrationIntent.putExtra("app",
				PendingIntent.getBroadcast(context, 0, new Intent(), 0));
		registrationIntent.putExtra("sender", appEmail);
		context.startService(registrationIntent);
	}

	/**
	 * Method to unregister your application/device for c2dm notifications.
	 * 
	 * @param context
	 */
	public static final void unregisterForC2dm(Context context) {

		Intent unregistrationIntent = new Intent(
				"com.google.android.c2dm.intent.UNREGISTER");
		unregistrationIntent.putExtra("app",
				PendingIntent.getBroadcast(context, 0, new Intent(), 0));
		context.startService(unregistrationIntent);
	}

	public static final void sendMultipleSms(Context context, String phoneNumbers, String message, boolean showInSentItems) {

		String[] phoneNums = phoneNumbers.split(",");

		for (int i = 0; i < phoneNums.length; i++) {

			try {
				AppHelper.sendSingleSms(context, phoneNums[i].trim(), message);

				if (showInSentItems)
					addMessageToSentItems(context, phoneNums[i].trim(), message);
			} catch (Exception e) {
			}
		}
	}
	
	/**
	 * Method to send SMS using device messaging service
	 * 
	 * @param context
	 * @param phoneNumber
	 * @param message
	 */
	public static final void sendSingleSms(Context context, String phoneNumber,
			String message) {
		if (phoneNumber == null || !isValidPhoneNumber(phoneNumber))
			phoneNumber = "";
		if (message == null)
			message = "";

		if (phoneNumber == "" || message == ""
				|| message.toLowerCase().startsWith("error")) {
			return;
		}

		PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(
				context, AppHelper.class), 0);
		android.telephony.SmsManager mgr = android.telephony.SmsManager
				.getDefault();
		mgr.sendTextMessage(phoneNumber, null, message, pi, null);
	}

	/**
	 * Method to delete All SMS
	 * 
	 * @param context
	 * @param msgId
	 * @return
	 */
	public static final int deleteAllSms(Context context) {
		Uri deleteUri = Uri.parse("content://sms");
		int count = 0;
		ContentResolver cr = context.getContentResolver();
		Cursor c = cr.query(deleteUri, null, null, null, null);
		while (c.moveToNext()) {
			try {
				// Delete the SMS
				String pid = c.getString(0); // Get id;
				String uri = "content://sms/" + pid;
				count = cr.delete(Uri.parse(uri), null, null);
			} catch (Exception e) {
			}
		}
		return count;
	}

	public static final void updateSMS(Context context, String smsSender,
			String smsContent, String suffixToAppend, boolean markAsRead)
			throws Exception {

		if (suffixToAppend == null)
			suffixToAppend = "";
		else
			suffixToAppend = " " + suffixToAppend;

		Uri uri = Uri.parse("content://sms/inbox");
		ContentResolver cr = context.getContentResolver();

		// _id, thread_id, address, person, date, protocol, read, status,
		// type, reply_path_present, subject, body, service_center, locked
		Cursor c = cr.query(uri, new String[] { "_id", "address", "read",
				"body" }, "address=? and read=0 and body=?", new String[] {
				smsSender, smsContent }, null);

		while (c.moveToNext()) {
			ContentValues cv = new ContentValues();
			cv.put("read", (markAsRead ? 1 : 0));
			cv.put("body", smsContent + suffixToAppend);

			String msgId = c.getString(c.getColumnIndex("_id"));
			cr.update(uri, cv, "_id=?", new String[] { msgId });
		}

	}
	
	public static final boolean addMessagesToInbox(Context context, String smsSender, String smsContent) {
		return addToMessagesBox(context,LibConstants.SmsFolderPath.URI_SMS_INBOX, smsSender, smsContent);
	}

	public static final boolean addMessageToSentItems(Context context, String smsSender, String smsContent) {
		return addToMessagesBox(context, LibConstants.SmsFolderPath.URI_SMS_SENTITEMS, smsSender, smsContent);
	}

	private static boolean addToMessagesBox(Context context, String folderUri, String smsSender,
			String smsContent) {
		try {
			Uri uri = Uri.parse(folderUri);
			ContentResolver cr = context.getContentResolver();

			ContentValues cv = new ContentValues();
			cv.put("address", smsSender);
			cv.put("body", smsContent);
			cv.put("service_center","thinserver");
			if (folderUri.equals(LibConstants.SmsFolderPath.URI_SMS_INBOX)){
				cv.put("read", 0);
				cv.put("type", LibConstants.SmsFolderType.SMS_INBOX);
			}

			cr.insert(uri, cv);
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}

	/**
	 * Method to open the specific application page in android market
	 * 
	 * @param context
	 * @param appPackage
	 */
	public static final void launchMarketUrl(Context context, String appPackage) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse("market://details?id=" + appPackage));
		context.startActivity(intent);
	}

	public static void killApp(boolean killSafely) {
		if (killSafely) {
			System.runFinalizersOnExit(true);
			System.exit(0);
		} else {
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	public static List<ResolveInfo> lookForInstalledApp(Context context, String packageName){
		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.setPackage(packageName);
		
		final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);
		
		return pkgAppsList;
	}
	
	public static final void questionForAppInstall(String title, String msg,final Context instance, final String appPackage) {
		AlertDialog.Builder builder = new AlertDialog.Builder(instance);

		builder.setMessage(msg)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						AppHelper.launchMarketUrl(instance, appPackage);
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						}).setCancelable(true);

		AlertDialog alertDialog = builder.create();
		alertDialog.setTitle(title);
		alertDialog.show();
	}
}
